const createError = require('http-errors');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
const fs = require('fs');
const {authToken} = require('./middleware/auth');
const {initGlobal, pageRouter} = require('./bin/config');
initGlobal()
const multer = require('multer');
const uploadFood = multer({ dest: 'assets/upload/shop/' })
const uploadUser = multer({ dest: 'assets/upload/user/' })
const uploadMap={'/food/upload':uploadFood,'/user/upload':uploadUser}
const app = express();

const indexRouter = require('./pages/index');
app.use((req, res, next) => {
    res.set({
        'Access-Control-Allow-Credentials': true,
        'Access-Control-Allow-Origin': req.headers.origin || '*',
        'Access-Control-Allow-Headers': 'X-Requested-With,Content-Type,Authorization',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS'
    })
    if (!pageRouter.includes(req.originalUrl) && !/^\/source/.test(req.originalUrl)) {
        res.set({
            'Content-Type': 'application/json; charset=utf-8'
        })
        req.method === 'OPTIONS' ? res.status(204).end() : next()
    } else {
        next()
    }
})
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({extended: false}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
fs.readdirSync(path.join(__dirname, 'routes')).forEach(file => {
    const filename = file.replace(/\.js$/, '');
    const RouterMap = require(`./routes/${filename}`);
    Object.keys(RouterMap).forEach((path) => {
        //初始化一个新的router
        const router = express.Router();
        app.use(`/${filename}${path}`,(req, res, next) => {
                const func = RouterMap[path];
                if(path.includes('upload')){
                    router.post('/',uploadMap[`/${filename}${path}`].single('file'),authToken, (req, res, next) => func(req, res, next));
                }else {
                    router.post('/',authToken, (req, res, next) => func(req, res, next));
                }
                router.get('/',authToken, (req, res, next) => func(req, res, next));
                router(req, res, next);
            }
        )
    })
});
// catch 404 and forward to error handler
app.use(function (req, res, next) {
    next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
    // set locals, only providing error in development
    res.set({'Content-Type': 'text/html; charset=utf-8'})
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};
    // render the error page
    res.status(err.status || 500);
    res.render('error');
});

module.exports = app;
